<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form v-if="mode !== 'detail'" :model="form" ref="formRef" label-width="120px" :rules="rules">
      <el-divider>基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小区名称" prop="name">
            <el-input v-model="form.name" clearable placeholder="请输入小区名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属区域" prop="region">
            <el-cascader
              v-model="form.region"
              :options="regionOptions"
              placeholder="请选择省/市/区"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小区类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择小区类型" clearable>
              <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="建造时间" prop="buildYear">
            <el-date-picker v-model="form.buildYear" type="date" placeholder="选择年份" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址" clearable />
          </el-form-item> 
        </el-col>
        <el-col :span="24">
          <el-form-item label="老旧小区改造情况" prop="renovation">
            <el-input v-model="form.renovation" clearable type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
        </el-row>
      <el-divider>楼栋信息</el-divider>
      <el-table :data="form.buildings" height="200px" border size="small" style="margin-bottom: 10px">
        <el-table-column label="住宅楼号" min-width="100">
          <template #default="{ row, $index }">
            <el-input v-if="editingIndex === $index" v-model="row.buildingNo" style="width: 100%" />
            <span v-else>{{ row.buildingNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单元数量" min-width="100">
          <template #default="{ row, $index }">
            <el-input-number :controls="false" v-if="editingIndex === $index" v-model="row.unitCount" :min="1" style="width: 100%"  />
            <span v-else>{{ row.unitCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="建造时间" min-width="100">
          <template #default="{ row, $index }">
            <el-date-picker v-if="editingIndex === $index" v-model="row.buildYear" value-format="YYYY" type="year" placeholder="选择年份" style="width: 100%" />
            <span v-else>{{ row.buildYear }}</span>
          </template>
        </el-table-column>
        <el-table-column label="建筑层数" min-width="100">
          <template #default="{ row, $index }">
            <el-input-number :controls="false" v-if="editingIndex === $index" v-model="row.floorCount" :min="1" style="width: 100%" />
            <span v-else>{{ row.floorCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="常住人口" min-width="100">
          <template #default="{ row, $index }">
            <el-input-number :controls="false" v-if="editingIndex === $index" v-model="row.population" :min="0" />
            <span v-else>{{ row.population }}</span>
          </template>
        </el-table-column>
        <el-table-column label="60岁以上人口" min-width="100">
          <template #default="{ row, $index }">
            <el-input-number :controls="false" v-if="editingIndex === $index" v-model="row.elderPopulation" :min="0" />
            <span v-else>{{ row.elderPopulation }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row, $index }">
            <template v-if="editingIndex === $index">
              <el-button size="small" type="primary" :icon="Check" @click="saveBuildingEdit($index)" />
              <el-button size="small" type="danger" :icon="Delete" @click="cancelBuildingEdit" />
            </template>
            <template v-else>
              <el-button size="small" type="primary" :icon="Edit" @click="editBuilding($index)" />
              <el-button size="small" type="danger" :icon="Delete" @click="removeBuilding($index)" />
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" size="small" @click="addBuilding">新增楼栋</el-button>
      <el-divider />
    </el-form>
    <div v-else style="padding: 24px;">
      <el-descriptions title="小区详情" :column="2" border>
        <el-descriptions-item label="小区名称">{{ form.name }}</el-descriptions-item>
        <el-descriptions-item label="所属区域">{{ getRegionText(form.region) }}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{ form.address }}</el-descriptions-item>
        <el-descriptions-item label="小区类型">{{ form.type }}</el-descriptions-item>
        <el-descriptions-item label="建造时间">{{ form.buildYear }}</el-descriptions-item>
        <el-descriptions-item label="老旧小区改造情况">{{ form.renovation }}</el-descriptions-item>
      </el-descriptions>
      <el-divider>楼栋信息</el-divider>
      <el-table :data="form.buildings" height="200px" border size="small">
        <el-table-column label="住宅楼号" prop="buildingNo" />
        <el-table-column label="单元数量" prop="unitCount" />
        <el-table-column label="建造时间" prop="buildYear" />
        <el-table-column label="建筑层数" prop="floorCount" />
        <el-table-column label="常住人口" prop="population" />
        <el-table-column label="60岁以上人口" prop="elderPopulation" />
      </el-table>
    </div>
    <template #footer v-if="mode !== 'detail'">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleOk">保存</el-button>
    </template>
    <template #footer v-else>
      <el-button @click="handleCancel">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, nextTick, computed } from 'vue';
import type { CommunityData, Building } from '@/types/community';
import guangzhouAreaData from '@/utils/guangzhou-area.json';
import { Delete, Edit,Check} from '@element-plus/icons-vue';
// 组件props定义
const props = defineProps<{
  modelValue: boolean; // 控制弹窗显示/隐藏
  mode: 'add' | 'edit' | 'detail'; // 弹窗模式：新增/编辑/详情
  formData: CommunityData; // 当前表单数据
  typeOptions?: string[]; // 小区类型选项
  regionOptions?: any[]; // 区域选项
  rules?: any; // 表单校验规则
}>();
// 事件定义
const emit = defineEmits(['update:modelValue', 'ok', 'cancel']);

const rules = ref({
  name: [{ required: true, message: '请输入小区名称', trigger: 'blur' }],
  region: [{ required: true, message: '请选择所属区域', trigger: 'blur' }],
  type: [{ required: true, message: '请选择小区类型', trigger: 'blur' }],
  buildYear: [{ required: true, message: '请选择建造时间', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
});

// 用于v-model的受控弹窗显示变量
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => emit('update:modelValue', val)
});

// 表单ref
const formRef = ref();
// 当前表单数据（深拷贝自props.formData）
const form = ref<CommunityData>({ ...props.formData });
// 弹窗标题
const dialogTitle = computed(() => {
  if (props.mode === 'add') return '新增';
  if (props.mode === 'edit') return '编辑';
  return '详情';
});

// 楼栋编辑相关
const editingIndex = ref(-1); // 当前正在编辑的楼栋索引
const backupBuilding = ref<Building | null>(null); // 编辑前备份

// 监听弹窗显示，重置表单和编辑状态
watch(() => props.modelValue, (val) => {
  formRef?.value?.resetFields();
  if (val) {
    form.value = { ...props.formData };
    editingIndex.value = -1;
  }
});

// 新增楼栋
const addBuilding = () => {
  form.value.buildings.push({
    buildingNo: '',
    unitCount: 1,
    buildYear: '',
    floorCount: 1,
    population: 0,
    elderPopulation: 0
  });
};
// 编辑楼栋
const editBuilding = (idx: number) => {
  editingIndex.value = idx;
  backupBuilding.value = { ...form.value.buildings[idx] };
};
// 保存楼栋编辑
const saveBuildingEdit = (idx: number) => {
  editingIndex.value = -1;
  backupBuilding.value = null;
};
// 取消楼栋编辑
const cancelBuildingEdit = () => {
  if (editingIndex.value > -1 && backupBuilding.value) {
    form.value.buildings[editingIndex.value] = { ...backupBuilding.value };
  }
  editingIndex.value = -1;
  backupBuilding.value = null;
};
// 删除楼栋
const removeBuilding = (idx: number) => {
  form.value.buildings.splice(idx, 1);
};

// 弹窗确定按钮
const handleOk = () => {
  emit('ok', { ...form.value }); // 向父组件传递表单数据
  emit('update:modelValue', false); // 关闭弹窗
};
// 弹窗取消按钮
const handleCancel = () => {
  emit('cancel');
  emit('update:modelValue', false);
};
// 弹窗关闭事件
const handleClose = () => {
  emit('update:modelValue', false);
};

// 根据区域代码数组获取区域文本
const getRegionText = (regionCodes: string[]) => {
  if (!regionCodes || regionCodes.length === 0) return '';
  const findLabel = (options: any[], codes: string[], index: number): string => {
    if (index >= codes.length) return '';
    const option = options.find(item => item.value === codes[index]);
    if (!option) return '';
    return option.label + (index < codes.length - 1 ? ' / ' : '') + findLabel(option.children || [], codes, index + 1);
  };
  return findLabel(props.regionOptions || guangzhouAreaData, regionCodes, 0);
};
</script> 